package worker

import (
	"GraduationProject/public/db"
	"GraduationProject/public/models"
	"GraduationProject/webserver/controllers/util"
	"github.com/gin-gonic/gin"
	"strconv"
)

// todo: 暂停 Worker
func Pause(c *gin.Context) {
	_, err := util.AdminFilter(c)
	if err != nil {
		return
	}
	workerID, err := util.PostFormInt(c, "worker_id")
	if err != nil {
		return
	}
	tx := db.DB.Begin()
	var worker models.Worker
	if tx.Set("gorm:query_option", "FOR UPDATE").
		Where("id = ?", workerID).First(&worker).Error != nil {
		tx.Rollback()
		util.FailedResponse(c, 10001, "无此程序")
		return
	}

	if worker.Status == models.WorkerStop {
		tx.Rollback()
		util.FailedResponse(c, 10003, "程序已停止运行")
		return
	}

	if tx.Model(&models.Worker{}).Where("id = ?", workerID).
		Update("status", models.WorkerPause).RowsAffected == 0 {
		tx.Rollback()
		util.FailedResponse(c, 10002, "暂停失败")
		return
	}

	// todo: 设置redis
	db.Redis.HSet(models.WorkerStatusKey, strconv.Itoa(workerID), models.WorkerPause)
	if tx.Commit().Error != nil {
		tx.Rollback()
		util.FailedResponse(c, 10004, "暂停失败")
		return
	}

	util.SuccessResponse(c)
}

func Begin(c *gin.Context) {
	_, err := util.AdminFilter(c)
	if err != nil {
		return
	}
	workerID, err := util.PostFormInt(c, "worker_id")
	if err != nil {
		return
	}

	tx := db.DB.Begin()
	var worker models.Worker
	if tx.Set("gorm:query_option", "FOR UPDATE").
		Where("id = ?", workerID).First(&worker).Error != nil {
		tx.Rollback()
		util.FailedResponse(c, 10001, "无此程序")
		return
	}

	if worker.Status == models.WorkerStop {
		tx.Rollback()
		util.FailedResponse(c, 10003, "程序已停止运行")
		return
	}

	if tx.Model(&models.Worker{}).Where("id = ?", workerID).
		Update("status", models.WorkerRunning).RowsAffected == 0 {
		tx.Rollback()
		util.FailedResponse(c, 10001, "启动失败")
		return
	}

	// todo: 设置redis
	db.Redis.HSet(models.WorkerStatusKey, strconv.Itoa(workerID), models.WorkerRunning)
	if tx.Commit().Error != nil {
		tx.Rollback()
		util.FailedResponse(c, 10004, "暂停失败")
		return
	}

	util.SuccessResponse(c)
}
